package com.yuntian.filter;

import com.yuntian.Vo.user.UserLoginVo;
import com.yuntian.context.BaseContext;
import com.yuntian.entity.User;
import com.yuntian.mapper.UserMapper;
import com.yuntian.properties.JwtProperties;
import com.yuntian.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class UserJwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        // 只处理用户路径
        if (!requestURI.startsWith("/user/")) {
            filterChain.doFilter(request, response);
            return;
        }

        String method = request.getMethod();
        log.info("用户请求: {} {}", method, requestURI);

        // 需要放行的用户路径
        if (shouldSkipUserFilter(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());

        if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
                Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
                Long userId = Long.valueOf(claims.get("userId").toString());
                User user = userMapper.getByUserId(userId);

                if (user == null) {
                    log.error("用户不存在，userId: {}", userId);
                    filterChain.doFilter(request, response);
                    return;
                }

                log.info("用户JWT解析成功，用户ID: {}", userId);

                UserLoginVo userLoginVo = UserLoginVo.builder()
                        .userId(userId)
                        .username(user.getUsername())
                        .build();

                log.info("用户 {} 认证成功", user.getUsername());
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(userLoginVo, null, userLoginVo.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);
                BaseContext.setCurrentId(userId);

            } catch (Exception e) {
                log.error("用户JWT解析失败: {}", e.getMessage(), e);
            }
        } else if (token == null) {
            log.warn("用户请求头中没有找到token");
        }

        filterChain.doFilter(request, response);
    }

    private boolean shouldSkipUserFilter(String requestURI) {
        return requestURI.equals("/user/user/login") || requestURI.equals("/user/user/register");
    }
}